package io.renren.modules.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.*;
import io.renren.modules.address_list.entity.V9AddressListEntity;
import io.renren.modules.address_list.service.V9AddressListService;
import io.renren.modules.member.entity.V9MemberEntity;
import io.renren.modules.member.service.V9MemberService;
import io.renren.modules.member_group.entity.V9MemberGroupEntity;
import io.renren.modules.member_group.service.V9MemberGroupService;
import io.renren.modules.news.service.V9NewsService;
import io.renren.modules.order.entity.V9OrderEntity;
import io.renren.modules.order.service.V9OrderService;
import io.renren.modules.order_pay.entity.V9OrderPayEntity;
import io.renren.modules.order_pay.service.V9OrderPayService;
import io.renren.modules.package_storage.entity.V9PackageStorageEntity;
import io.renren.modules.package_storage.service.V9PackageStorageService;
import io.renren.modules.pay_account.entity.V9PayAccountEntity;
import io.renren.modules.pay_account.service.V9PayAccountService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController extends AbstractController{
	@Autowired
	private V9OrderService v9OrderService;
	@Autowired
	private V9PackageStorageService v9PackageStorageService;
	@Autowired
	private V9AddressListService v9AddressListService;
	@Autowired
	private V9PayAccountService v9PayAccountService;
	@Autowired
	private V9MemberService  v9MemberService;
	@Autowired
	private V9MemberGroupService v9MemberGroupService;
	@Autowired
	private V9OrderPayService v9OrderPayService;
	@Autowired
	private V9NewsService v9NewsService;

	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = v9OrderService.getOrderList(params);
		return R.ok().put("page", page);
	}
	@RequestMapping("/listPackage")
	public R listPackage(@RequestParam Map<String, Object> params) {
		V9MemberEntity userKehu = getUserKehu();
		System.out.println(userKehu.toString());
		params.put("u_code", userKehu.getUsername());
		PageUtils page = v9PackageStorageService.getPackageList(params);
		return R.ok().put("page", page);
	}
	@RequestMapping("/listorder")
	public R listorder(@RequestParam Map<String, Object> params) {
		V9MemberEntity userKehu = getUserKehu();
		params.put("uid", userKehu.getUserid());
		PageUtils page = v9OrderService.getOrderList(params);

		return R.ok().put("page", page);
	}


	/**
	 *提交打包
	 * @return
	 */
	@RequestMapping("/tijiaodabao")
	public R putPacking(String ids,String desc,boolean paizao,boolean fast){
		V9MemberEntity userKehu = getUserKehu();
		v9OrderService.dabao(ids,userKehu,desc,paizao,fast);
 		return R.ok();

	}
	@RequestMapping("/addresssave")
	public R addresssave(@RequestBody V9AddressListEntity v9AddressList){
		Integer kehuid=getUserKehu().getUserid();
		v9AddressList.setUid(kehuid);
		v9AddressListService.save(v9AddressList);
		return R.ok();
	}
	@RequestMapping("/addressupdate")
	public R addressupdate(@RequestBody V9AddressListEntity v9AddressList){
		v9AddressListService.updateById(v9AddressList);
		return R.ok();
	}
	@RequestMapping("/addrdelete")
	public R addrdelete(Integer id){
		v9AddressListService.removeById(id);
		return R.ok();
	}

	@RequestMapping("/addressadd")
	public R addressadd(String addrid){

		V9AddressListEntity addressListEntity=v9AddressListService.getById(Integer.parseInt(addrid));

		return R.ok().put("address",addressListEntity);
	}


	@RequestMapping("/addresslist")
	public R addresslist(){
		Integer kehuid=getUserKehu().getUserid();
		List<V9AddressListEntity> addressListEntity = v9AddressListService.list(new QueryWrapper<V9AddressListEntity>().eq("uid", kehuid).orderByDesc("id"));

		return R.ok().put("list",addressListEntity);
	}
	@RequestMapping("/getuseraddr")
	public R getuseraddr(){
		Integer kehuid=getUserKehu().getUserid();
		//kehuid=2342;
		V9AddressListEntity one = v9AddressListService.getOne(new QueryWrapper<V9AddressListEntity>().eq("uid", kehuid).eq("isdefault", 1));

		return R.ok().put("address",one);
	}


	/**
	 * 我的 用户信息
	 * @return
	 */

	@RequestMapping("/getuserinfo")
	public R getuserinfo(){

	   V9MemberEntity memberEntity=getUserKehu();
	   //包裹
	   int q=v9PackageStorageService.count(new QueryWrapper<V9PackageStorageEntity>().eq("u_code",memberEntity.getUsername()).eq("status",0));
	   //未打包
	   int count = v9OrderService.count(new QueryWrapper<V9OrderEntity>().eq("uid", memberEntity.getUserid()).eq("order_status", 0));
	   //待付款
	   int count2 = v9OrderService.count(new QueryWrapper<V9OrderEntity>().eq("uid", memberEntity.getUserid()).eq("order_status", 1));
	   //转运中
	   int count3 = v9OrderService.count(new QueryWrapper<V9OrderEntity>().eq("uid", memberEntity.getUserid()).eq("order_status", 2));
	   //签收
	   int count4 = v9OrderService.count(new QueryWrapper<V9OrderEntity>().eq("uid", memberEntity.getUserid()).eq("shipping_status", 4));
	   return R.ok().put("user",memberEntity).put("packnum",q).put("status1", count).put("status2", count2).put("status3", count3).put("status4", count4);

	}
	/**
	 * 支付界面用户信息
	 * @return
	 */
	@RequestMapping("/userinfo")
	public R userinfo(){
		V9MemberEntity memberEntity=getUserKehu();
		V9MemberGroupEntity byId = v9MemberGroupService.getOne(new QueryWrapper<V9MemberGroupEntity>().eq("starnum",memberEntity.getVip()));
		Integer freeCardUse=memberEntity.getFreeCardUse();
		List<V9MemberGroupEntity> list = v9MemberGroupService.list(new QueryWrapper<V9MemberGroupEntity>().le("starnum", memberEntity.getVip()).orderByDesc("starnum"));
		Integer totalCard=0;
		for (V9MemberGroupEntity v9MemberGroupEntity : list) {
			String yhq=v9MemberGroupEntity.getYhq();
			if (!yhq.equals("0")) {
				String yhnum=StringUtils.split(yhq, "*")[1];
				totalCard=totalCard+Integer.parseInt(yhnum);
			}

		}
		freeCardUse=totalCard-freeCardUse;
		memberEntity.setFreeCardUse(freeCardUse);
		String nowyhq=list.get(0).getYhq();
		if (!nowyhq.equals("0")) {
			nowyhq=StringUtils.split(nowyhq,"*")[0];
		}
		memberEntity.setFreeCardMoney(Integer.parseInt(nowyhq));
		memberEntity.setDiscount(list.get(0).getDiscount());
		memberEntity.setDiscountTxt(list.get(0).getDiscountText());
		return R.ok().put("user",memberEntity);
	}
	@RequestMapping("/pay")
	public R pay(@RequestBody JSONObject jsonParam){
		V9MemberEntity memberEntity=getUserKehu();
//		orderId:this.orderInfo.orderId,
//        paypass:this.paypass,
//        integral:this.totalPoint, //积分
//        total_fee:this.order_pay.total_fee, //总金额
//        member_fee:this.order_pay.total_fee, //会员价
//        pay_fee:this.order_pay.pay_fee, //实际支付
		String orderId = jsonParam.getString("orderId");
		String payment = jsonParam.getString("payment");
		String total_fee = jsonParam.getString("total_fee");
		String member_fee = jsonParam.getString("member_fee");
		String pay_fee = jsonParam.getString("pay_fee");
		String paypass = jsonParam.getString("paypass");
		String activity_fee = jsonParam.getString("activity_fee");
		String integralFee = jsonParam.getString("integral_fee");
		String integral = jsonParam.getString("integral");
		if(payment.equals("5")){
			String encrypt = memberEntity.getEncrypt();
			String pass = memberEntity.getPayword();
			String newpass=CommonUtils.encrypt(paypass, encrypt);
			if (!pass.equals(newpass)) {
				return R.error("支付密码错误");
			}
			V9OrderPayEntity payEntity=new V9OrderPayEntity();
			payEntity.setSpbillno(CommonUtils.createOrderSn());
			payEntity.setPayStatus(2);
			payEntity.setTotalFee(CommonUtils.stringTwoBigDecimal(total_fee));
			payEntity.setMemberFee(CommonUtils.stringTwoBigDecimal(member_fee));
			payEntity.setPayFee(CommonUtils.stringTwoBigDecimal(pay_fee));
			payEntity.setPayment(payment);
			payEntity.setActivityFee(Integer.parseInt(activity_fee));
			payEntity.setIntegralFee(CommonUtils.stringTwoBigDecimal(integralFee));
			payEntity.setIntegral(Integer.parseInt(integral));
			payEntity.setUserId(memberEntity.getUserid());
			v9OrderPayService.save(payEntity);
		}


		V9OrderEntity entity=new V9OrderEntity();
		entity.setOrderId(Integer.parseInt(orderId));
		entity.setOrderStatus(2);
		//v9OrderService.updateById(entity);
		return R.ok();
	}


	//评价
	@RequestMapping("/comment")
	public R comment(String rate,String content){
		Integer userid =getUserKehu().getUserid();
		return R.ok();
	}
	@RequestMapping("/parcelcount")
	public R parcelcount(String uCode){
		return v9PackageStorageService.parcelcount(uCode);
	}
	/**
	 * 确认收货
	 * @return
	 */
	@RequestMapping("/shouhuo")
	public R shouhuo(Integer orderId){
		V9OrderEntity entity=new V9OrderEntity();
		entity.setOrderId(orderId);
		entity.setShippingStatus(4);
		v9OrderService.updateById(entity);
		return R.ok();
	}

	//会员等级
	@RequestMapping("/vipinfo")
	public R vipinfo(){
		V9MemberEntity userKehu = getUserKehu();
		V9MemberGroupEntity vip = v9MemberGroupService.getOne(new QueryWrapper<V9MemberGroupEntity>().eq("starnum",userKehu.getVip()));

		V9MemberGroupEntity vip2 = v9MemberGroupService.getOne(new QueryWrapper<V9MemberGroupEntity>().eq("starnum",userKehu.getVip()+1));
	 	int num = vip2.getMoney() - userKehu.getVipExpTotal();
		return R.ok().put("vip",vip).put("num",num).put("vip2",vip2);
	}

	@RequestMapping("/memberCentre")
	public R memberCentre(){
		V9MemberEntity userKehu = getUserKehu();
		v9MemberService.updateById(userKehu);
		return R.ok();
	}
	/**
	 * 充值记录
	 *
	 * @return
	 */
	@RequestMapping("/payAccout")
	public R payAccoutInfo(){
		Integer kehuid=getUserKehu().getUserid();
		List<V9PayAccountEntity> payAccountEntities = v9PayAccountService.list(new QueryWrapper<V9PayAccountEntity>().eq("userid", kehuid).orderByDesc("id"));
		return R.ok().put("list",payAccountEntities);
	}

	/**
	 * 运费
	 * @return
	 */
	@RequestMapping("/yunFei")
	public R yunFei(){
		return v9OrderPayService.getYunFei();
	}

	/**
	 * 邮箱验证
	 *
	 * @return
	 */
	@RequestMapping("/VerifyMail")
	public R VerifyMail(String mail){

		return v9OrderService.VerifyMail(mail);

	}


	/**
	 * 验证验证码
	 * @return
	 */
	@RequestMapping("/checkCode")
	public R checkCode(String mail,String code){
		return v9OrderService.checkCode(mail, code);
	}


	/**
	 * 生成二维码
	 * @param response
	 */
	@RequestMapping("/QRCode")
	public void QRCode(HttpServletResponse response) throws Exception {

		V9MemberEntity userKehu = getUserKehu();
		String inviteCode = userKehu.getInviteCode();
		String text = "http://www.kuaizi56.com/"+userKehu;

		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		File file = new DefaultResourceLoader().getResource("").getFile();
		File f = new File(file.getPath() + File.separator + "static"+File.separator+"theme" +File.separator+"images"+ File.separator + "logo.png");

		//获取图片验证码
		BufferedImage image = QRCodeUtil.createImage(text,f.getPath(),true);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);

	}


	@RequestMapping("/listNews")
	public R listNews(@RequestParam Map<String, Object> params) {

		PageUtils page = v9NewsService.getNewsList(params);
		return R.ok().put("page", page);
	}


}
